<template>
  <!-- 受限空间作业票申请 -->
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="ticketForm" :rules="rules" labelPosition="top" label-width="70vw">
        <view class="hidden-title">信息填写</view>

        <cu-cell-group>
          <uni-forms-item name="workName">
            <cu-cell title="受限空间名称" column required>
              <uni-easyinput
                type="textarea"
                v-model="ticketForm.workName"
                placeholder="根据实际情况填写(限20字)"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="insetName">
            <cu-cell title="受限空间内原有介质名称" column required>
              <uni-easyinput
                type="textarea"
                v-model="ticketForm.insetName"
                placeholder="根据实际情况填写(限20字)"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="libId">
            <hazardous-medium-select v-model="ticketForm.libId" label="危害介质" placeholder="请选择" required />
          </uni-forms-item>
        </cu-cell-group>

        <cu-cell-group class="bor-top">
          <uni-forms-item name="principal">
            <cu-cell
              title="作业负责人"
              required
              link
              placeholder="请选择"
              :description="ticketForm.principalLabel"
              @click="showUserSelector()"
            ></cu-cell>
          </uni-forms-item>

          <uni-forms-item name="deptId">
            <cu-cell
              title="受限空间所属单位"
              required
              link
              placeholder="请选择"
              :description="ticketForm.deptLabel"
              @click="$refs.deptSelectorRef.open()"
            ></cu-cell>
          </uni-forms-item>

          <uni-forms-item name="startTime">
            <uni-datetime-picker
              hide-second
              :start="now"
              :end="endTime"
              type="datetime"
              @change="onTimeChange($event, 'startTime')"
            >
              <cu-cell
                title="计划开始时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.startTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
          <uni-forms-item name="endTime">
            <uni-datetime-picker
              hide-second
              :start="startTime"
              type="datetime"
              @change="onTimeChange($event, 'endTime')"
            >
              <cu-cell
                title="计划结束时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.endTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>

      <dept-selector ref="deptSelectorRef" @change="deptSelectorChange"></dept-selector>
    </view>

    <!-- 用户选择器 v2 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :checkList="deptUserSelectProps.checkList"
      @change="onDeptUserChange"
    ></cu-dept-user-select>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellMultiLine from '@/components/cu-cell/cu-cell-multi-line.vue'
import CuSelect from '@/components/cu-select/cu-select.vue'
import DeptSelector from '@/components/dept-selector/index.vue'
import DataPicker from '@/components/data-picker/index.vue'
import dayjs from 'dayjs'
import { getGasLibs } from '../../../api/spw/ticketApply'
import { cloneDeep } from 'lodash'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import HazardousMediumSelect from '@/components/hazardous-medium-select/hazardous-medium-select.vue'

export default {
  components: {
    HazardousMediumSelect,
    CuDeptUserSelect,
    CuCellGroup,
    CuCell,
    CuCellMultiLine,
    CuSelect,
    DeptSelector,
    DataPicker
  },
  props: {
    ticketInfo: {
      type: Object,
      default: () => {}
    },
    templateId: {
      type: [String, Number],
      default: ''
    },
    unitType: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    const validatorLib = (rule, value, data, callback) => {
      if (value.length) {
        return true
      } else {
        return callback('不能为空')
      }
    }
    return {
      deptUserSelectProps: {
        checkList: []
      },
      ticketForm: {
        specialWorkType: '',
        specialWorkTypeLabel: '',
        workName: '', // 受限空间名称 作业名称
        deptId: '', // 受限空间所属单位
        deptLabel: '', // 受限空间所属单位
        insetName: '', // 受限空间内原有介质名称
        startTime: '', // 实施开始时间
        endTime: '', // 实施结束时间
        principal: '', // 作业负责人
        principalLabel: '', // 作业负责人名字
        libId: [] // 危险介质
      },
      selectUserType: 1,
      nodeIdx: '',
      result: {},
      now: dayjs(new Date()).format('YYYY-MM-DD HH:mm'),
      rules: {
        libId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            },
            {
              validateFunction: validatorLib
            }
          ]
        },
        workName: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        startTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        endTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        deptId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        insetName: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        principal: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  computed: {
    endTime() {
      if (!this.ticketForm.endTime) {
        return ''
      }
      return dayjs(this.ticketForm.endTime).valueOf() - 60 * 60 * 1000
    },
    startTime() {
      if (!this.ticketForm.startTime) {
        return ''
      }
      return dayjs(this.ticketForm.startTime).valueOf() + 60 * 60 * 1000
    }
  },
  watch: {
    ticketInfo: {
      async handler(val) {
        console.log('v', val)
        if (val) {
          Object.keys(this.ticketInfo).map((k) => {
            this.ticketForm[k] = cloneDeep(this.ticketInfo[k])
          })
        }
      },
      // deep: true,
      immediate: true
    }
  },
  methods: {
    onDeptUserChange(val) {
      if (!val) {
        return
      }
      this.ticketForm.principal = val[0].userId
      this.ticketForm.principalLabel = val[0].name
    },
    deptSelectorChange(item) {
      this.ticketForm.deptId = item.value
      this.ticketForm.deptLabel = item.name
    },
    showUserSelector() {
      this.deptUserSelectProps.checkList = this.ticketForm.principal
        ? [{ userId: this.ticketForm.principal, name: this.ticketForm.principalLabel }]
        : []
      this.$refs.deptUserSelectRef.open()
    },

    onTimeChange(val, key) {
      if (val.trim().includes(' ')) {
        this.ticketForm[key] = val.trim()
      } else {
        this.$modal.showToast('请选择日期和时间')
      }
    },

    async submit() {
      await this.$refs.form.validate()
      const start = dayjs(this.ticketForm.startTime).valueOf()
      const end = dayjs(this.ticketForm.endTime).valueOf()
      const oneHour = 60 * 60 * 1000
      if (end - start < oneHour) {
        this.$modal.showToast('开始时间与结束时间间隔必须大于60分钟')
        return
      }

      this.result = {
        ...this.ticketForm,
        procDefId: this.procDefId,
        workType: this.ticketForm.specialWorkType,
        workId: this.ticketForm.workId
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.other-type {
  background: #f5f5f5;
  padding: 20rpx;
  margin-top: 10rpx;
  .input {
    text-align: left;
  }
}

.lib-radio ::v-deep .cu-select-item {
  width: auto;
  margin: 0 10px;
}
</style>
